package com.mingmen.supplier.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.supplier.R;
import com.mingmen.supplier.activity.AuditDetailActivity;
import com.mingmen.supplier.activity.CommodityShopActivity;
import com.mingmen.supplier.activity.CommodityShopManagerActivity;
import com.mingmen.supplier.adapter.AuditListAdapter;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.model.AuditListModel;
import com.mingmen.supplier.model.EventBean;
import com.mingmen.supplier.refresh.ClassicsFooter;
import com.mingmen.supplier.refresh.ClassicsHeader;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class ShenHeListFragment extends BaseFragment implements AuditListAdapter.OnItemClickListener {
    @BindView(R.id.card_title_tv)
    TextView cardTitleTv;
    Unbinder unbinder;
    private String mTitle;

    public static ShenHeListFragment getInstance(String title) {
        ShenHeListFragment sf = new ShenHeListFragment();
        sf.mTitle = title;
        return sf;
    }

    @BindView(R.id.recycle_shopo)
    RecyclerView mRecyclerView;
    @BindView(R.id.layout_nodata)
    LinearLayout layout_nodata;


    AuditListAdapter commodityAdapter;

    List<AuditListModel.DataBean> dataList = new ArrayList<>();

    LinearLayoutManager linearLayoutManager;

    String token;
    private IntentFilter intentFilter;
    private MyBroadcastReceiver myBroadcastReceiver;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    int pageNumber = 1;
    int totalPage;
    @BindView(R.id.layout_alldata)
    LinearLayout layout_alldata;

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //系统服务类
            String pos = intent.getStringExtra("pos");
            Log.d("pospospos", pos);

        }
    }

    @Override
    public View initView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fr_shenhelist, null);
        unbinder = ButterKnife.bind(this, v);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        EventBus.getDefault().register(this);
        registerBroad();
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        linearLayoutManager = new LinearLayoutManager(getActivity());
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        commodityAdapter = new AuditListAdapter(getActivity(), dataList);
        mRecyclerView.setAdapter(commodityAdapter);
        commodityAdapter.setOnItemClickListener(this);
        commodityAdapter.setOnItemClickListener(this);
        getData(token, "", mTitle, "", pageNumber);

        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                if (dataList.size() > 0) {
                    dataList.clear();
                }
                pageNumber = 1;

//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                getData(token, "", mTitle, "", pageNumber);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (pageNumber >= totalPage) {
                    Toast.makeText(getActivity(), "已到最后一页", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishLoadMore(false);//传入false表示加载失败
                } else {
                    pageNumber++;

//                    getData(token, "", mTitle, "",pageNumber);
                    HttpResponse.getSupplierCommodity(token, "", mTitle, "", pageNumber, new StringCallback(getActivity()) {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.d("GetData", s);

                            AuditListModel auditListModel = new AuditListModel();
                            auditListModel = GsonUtil.GsonToBean(s, AuditListModel.class);
                            dataList.addAll(auditListModel.getData());
                            totalPage = auditListModel.getTotalPage();
                            if (dataList.size() == 0) {
                                layout_nodata.setVisibility(View.VISIBLE);
                            } else {
                                layout_nodata.setVisibility(View.GONE);
                            }
                            commodityAdapter.setDataList(dataList);
                        }

                        @Override
                        public void onAfter(String s, Exception e) {
                            super.onAfter(s, e);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            layout_nodata.setVisibility(View.VISIBLE);
                            refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                        }
                    });
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                }


            }
        });


        commodityAdapter.setOnItemClickListener(new AuditListAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int pos, List<AuditListModel.DataBean> myLiveList) {
                Intent intent = new Intent(getActivity(), AuditDetailActivity.class);
                Log.d("commodityIdcommodityId", myLiveList.get(pos).getCommodityId() + "");
//                        CommodityShopManagerActivity
                intent.putExtra("commodityId", myLiveList.get(pos).getCommodityId() + "");
                startActivity(intent);
              /*  intent = new Intent(CommodityShopActivity.this, AuditDetailActivity.class);
                Log.d("commodityIdcommodityId", myLiveList.get(pos).getCommodityId() + "");
//                        CommodityShopManagerActivity
                intent.putExtra("commodityId", myLiveList.get(pos).getCommodityId() + "");
                startActivity(intent);*/
            }
        });

        return v;
    }

    @Override
    public void initData() {

    }

    public void getData(String token, String categoryId, String state, String keyword, int pageNumber) {
        HttpResponse.getSupplierCommodity(token, categoryId, state, keyword, pageNumber, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("GetData", s);
                if (dataList.size() > 0) {
                    dataList.clear();
                }
                AuditListModel auditListModel = new AuditListModel();
                auditListModel = GsonUtil.GsonToBean(s, AuditListModel.class);
                dataList.addAll(auditListModel.getData());
                totalPage = auditListModel.getTotalPage();
                if (dataList.size() == 0) {
                    layout_nodata.setVisibility(View.VISIBLE);
                } else {
                    layout_nodata.setVisibility(View.GONE);
                }
                commodityAdapter.setDataList(dataList);
            }

            @Override
            public void onAfter(String s, Exception e) {
                super.onAfter(s, e);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                layout_nodata.setVisibility(View.VISIBLE);
                refreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.card_title_tv)
    public void onViewClicked() {
    }

    @Override
    public void onItemClickListener(View view, int pos, List<AuditListModel.DataBean> myLiveList) {
        switch (view.getId()) {
            case R.id.text_manager:
                Toast.makeText(mContext, "增加", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(getActivity(), CommodityShopManagerActivity.class));
                break;
        }

    }

    public void registerBroad() {
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.mingmen.supplier.fragment.ShenHeListFragment");
        myBroadcastReceiver = new MyBroadcastReceiver();
        //注册广播
        getActivity().registerReceiver(myBroadcastReceiver, intentFilter);
    }
    public void onEventMainThread(EventBean eventBean) {
        if (eventBean.getSendCode()==25){
            getData(token, "", mTitle, eventBean.getSendStr(), pageNumber);
        }else if (eventBean.getSendCode()==26){
            getData(token, "", mTitle, "", pageNumber);
        }


    }
}